package a_doubleWrite;

import java.util.Comparator;
import java.util.PriorityQueue;

/**
 * todo
 *
 * @author: luolidong
 * @create: 2021-07-19 18:54
 * @version: 1.0
 */
public class L215_queue {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> queue = new PriorityQueue<>();
        for(int n:nums){
            if(queue.isEmpty()){
                queue.offer(n);
            }else {
                if(queue.size()<k){
                    queue.offer(n);
                }else {
                    if(n>queue.peek()){
                        queue.poll();
                        queue.offer(n);
                    }
                }
            }
        }
        return queue.peek();
    }
    public int findKthMinest(int[] nums, int k) {
        //默认升序，现在要降序 3 2 1
        PriorityQueue<Integer> queue = new PriorityQueue<>((o1, o2) -> o2-o1);
        for(int n:nums){
            if(queue.isEmpty()){
                queue.offer(n);
            }else {
                if(queue.size()<k){
                    queue.offer(n);
                }else {
                    if(n<queue.peek()){
                        queue.poll();
                        queue.offer(n);
                    }
                }
            }
        }
        return queue.peek();
    }

    public static void main(String[] args) {
        int[] nums = {23, 1, 3, 54, 21, 56, 12};
        L215_queue l215_queue = new L215_queue();
        int kthLargest = l215_queue.findKthLargest(nums, 3);
        System.out.println("kthLargest = " + kthLargest);

        int kthMinest = l215_queue.findKthMinest(nums, 3);
        System.out.println("kthMinest = " + kthMinest);
    }
}
